#!/bin/bash

# Dumbo 部署脚本
# 用于在 AWS EC2 实例上部署和运行 Dumbo 共识实验

# 1. 设置环境变量
export IP_LIST="98.80.84.148,44.241.66.49,13.202.21.116,54.170.130.76"
export HOST_LIST="ubuntu@98.80.84.148,ubuntu@44.241.66.49,ubuntu@13.202.21.116,ubuntu@54.170.130.76"
export NODE_COUNT=4
export RUN_DURATION=60  # 实验持续时间（秒）
# export KEY_FILE="~/.ssh/dumbo-aws-key.pem"

# 2. 在远程节点部署
cd /home/dumbo/benchmark

echo "========================================="
echo "  Dumbo 分布式部署"
echo "========================================="
echo "节点列表: $IP_LIST"
echo "节点数量: $NODE_COUNT"
echo "运行时长: ${RUN_DURATION}秒"
echo "========================================="
echo ""

echo "--- [阶段 1] 安装依赖 ---"
fab -H $HOST_LIST -i $KEY_FILE setup

echo ""
echo "--- [阶段 2] 部署代码（从 GitHub 拉取） ---"
fab -H $HOST_LIST -i $KEY_FILE deploy

echo ""
echo "--- [阶段 3] 生成配置文件 ---"
fab -H $HOST_LIST -i $KEY_FILE generate-config --hosts-str="$IP_LIST"

echo ""
echo "--- [阶段 4] 清理旧数据 ---"
fab -H $HOST_LIST -i $KEY_FILE clean

echo ""
echo "--- [阶段 5] 启动节点 ---"
fab -H $HOST_LIST -i $KEY_FILE launch-node --hosts-str="$IP_LIST"

echo ""
echo "--- 实验运行中，持续 $RUN_DURATION 秒 ---"
for i in $(seq 1 $RUN_DURATION); do
    if [ $((i % 10)) -eq 0 ]; then
        echo "  已运行 $i 秒..."
    fi
    sleep 1
done

echo ""
echo "--- [阶段 6] 停止节点 ---"
fab -H $HOST_LIST -i $KEY_FILE kill

echo ""
echo "--- [阶段 7] 收集日志 ---"
fab -H $HOST_LIST -i $KEY_FILE collect-logs

echo ""
echo "========================================="
echo "  部署完成！"
echo "========================================="
echo "日志已保存到 ./logs/ 目录"
echo ""
echo "日志文件说明："
echo "  - node-{id}.out: 标准输出日志"
echo "  - node_{id}.log: Dumbo 运行日志"
echo ""